import { Component, forwardRef, OnInit } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { NzSelectOptionInterface } from 'ng-zorro-antd/select';
import { TemplateService } from 'src/app/common/providers';

@Component({
  selector: 'app-drop-select',
  templateUrl: './drop-select.component.html',
  styleUrls: ['./drop-select.component.less'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => DropSelectComponent),
      multi: true,
    },
  ],
})
export class DropSelectComponent implements OnInit, ControlValueAccessor {
  // 控件值
  value: any = null;
  // 控件的禁用属性
  disabled = false;
  // 控件 change 事件的回调
  onChange: (_: any) => void;
  onBlur: () => void;
  // nz-select 组件选项数据
  options: NzSelectOptionInterface[] = [];

  constructor(private templateServ: TemplateService) {}

  ngOnInit(): void {
    this.templateServ.getUserList().subscribe((res) => {
      if (res.success) {
        this.options = res.data.map((item) => {
          return {
            label: item.name,
            value: item.id,
          };
        });
      }
    });
  }

  /**
   * 写入值到控件
   * @param value 写入的值
   */
  writeValue(value: any): void {
    if (value) {
      this.value = value;
    }
  }

  /**
   * 注册控件 change 事件的回调函数
   * @param fn 控件 change 事件的回调函数
   */
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  /**
   * 注册控件 touch 事件（blur 事件）的回调函数
   * @param fn 控件 touch 事件的回调函数
   */
  registerOnTouched(fn: any): void {
    this.onBlur = fn;
  }

  /**
   * 设置控件禁用状态
   * @param isDisabled 是否禁用
   */
  setDisabledState(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }
}
